package dxn.nl.file.center.netty.client;

import io.netty.channel.socket.SocketChannel;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;

import java.time.LocalDateTime;
import java.util.*;

public class AppRegisterUtil {
    private HashMap<String,SocketChannel> socketChannels = new HashMap<>();
    private int currentIndex = 0;

    public AppRegisterUtil() {
    }

    public boolean contains(String sessionId)
    {
        return socketChannels.containsKey(sessionId);
    }

    public boolean remove(String appSessionId)
    {
        socketChannels.remove(appSessionId);
        return true;
    }

    public void add(String appSessionId,SocketChannel channel)
    {
        socketChannels.put(appSessionId,channel);
    }

    public Pair<String,SocketChannel> getDealChannel(String sessionId)
    {
        if(socketChannels.size() == 0)
        {
            return null;
        }

        if(StringUtils.isNotBlank(sessionId)) {
            SocketChannel channelDto = socketChannels.get(sessionId);
            return Pair.of(sessionId,channelDto);
        }

        currentIndex = (currentIndex + 1) % socketChannels.size();
        int i=0;
        for(Map.Entry<String,SocketChannel> entry:socketChannels.entrySet())
        {
            if(i>=currentIndex)
            {
                return Pair.of(entry.getKey(),entry.getValue());
            }
        }
        return Pair.of(sessionId,null);
    }
}
